<template>
  <div class="admin-dashboard">
    <el-card>
      <h2>管理员仪表盘</h2>
      <p>欢迎来到生鲜供应链管理系统后台！</p>
      <el-row :gutter="20" class="dashboard-stats">
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-title">用户总数</div>
            <div class="stat-value">{{ stats.total_users || 0 }}</div>
            <div class="stat-trend">
              <span :class="{ 'up': userGrowth > 0, 'down': userGrowth < 0 }">
                {{ userGrowth > 0 ? '+' : '' }}{{ userGrowth }}%
              </span>
              较上月
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-title">产品总数</div>
            <div class="stat-value">{{ stats.total_products || 0 }}</div>
            <div class="stat-trend">
              <el-tag size="small" type="warning" v-if="stats.low_stock_products > 0">
                {{ stats.low_stock_products }} 个库存不足
              </el-tag>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-title">订单总数</div>
            <div class="stat-value">{{ stats.total_orders || 0 }}</div>
            <div class="stat-trend">
              <el-tag size="small" type="danger" v-if="stats.pending_orders > 0">
                {{ stats.pending_orders }} 个待处理
              </el-tag>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-title">配送任务</div>
            <div class="stat-value">{{ stats.total_deliveries || 0 }}</div>
            <div class="stat-trend">
              <el-tag size="small" type="info" v-if="stats.pending_deliveries > 0">
                {{ stats.pending_deliveries }} 个进行中
              </el-tag>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="dashboard-charts">
        <!-- 用户注册趋势 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div style="text-align:center; font-weight:bold; font-size:18px; margin-bottom: -8px;">订单趋势分析</div>
              <div class="chart-header">
                <span>订单趋势</span>
                <el-radio-group v-model="userChartRange" size="small">
                  <el-radio-button label="week">本周</el-radio-button>
                  <el-radio-button label="month">本月</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <v-chart class="chart" :option="orderTrendOption" autoresize ref="chartInstance" />
          </el-card>
        </el-col>
        
        <!-- 订单分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>订单状态分布</span>
              </div>
            </template>
            <OrderStatusPie
              :data="stats.order_distribution"
              :loading="stats.order_distribution.length === 0"
              :theme="theme"
            />
          </el-card>
        </el-col>
      </el-row>

      <!-- 系统动态区域 -->
      <el-card class="timeline-card timeline-scroll-card">
        <template #header>
          <div class="chart-header">
            <span>系统动态</span>
          </div>
        </template>
        <div class="timeline-scroll-content">
          <div class="activity-cards">
            <div
              v-for="(activity, index) in systemActivities"
              :key="index"
              class="activity-card"
              :style="{ background: '#e8f8ee' }"
            >
              <span class="activity-icon">
                <el-icon v-if="activity.icon === 'ShoppingCart'">
                  <ShoppingCart />
                </el-icon>
                <el-icon v-else-if="activity.icon === 'User'">
                  <User />
                </el-icon>
                <el-icon v-else-if="activity.icon === 'Van'">
                  <Van />
                </el-icon>
                <el-icon v-else-if="activity.icon === 'Check'">
                  <Check />
                </el-icon>
                <el-icon v-else-if="activity.icon === 'Warning'">
                  <Warning />
                </el-icon>
                <el-icon v-else>
                  <Bell />
                </el-icon>
              </span>
              <span class="activity-content">{{ activity.content }}</span>
              <span class="activity-time">{{ activity.time ? new Date(activity.time).toLocaleString() : '--' }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { getToken } from '@/utils/auth'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import * as echarts from 'echarts/core'
import VChart from 'vue-echarts'
import OrderStatusPie from './OrderStatusPie.vue'
import { ShoppingCart, User, Van, Check, Warning, Bell } from '@element-plus/icons-vue'

// 注册必要的 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

const stats = ref({
  total_users: 0,
  total_products: 0,
  total_orders: 0,
  total_deliveries: 0,
  pending_orders: 0,
  low_stock_products: 0,
  pending_deliveries: 0,
  user_growth: 0,
  order_trend: [],
  order_distribution: [],
  recent_activities: []
})

const userChartRange = ref('week')
const userGrowth = computed(() => stats.value.user_growth)
const recentActivities = ref([])

// 在 stats ref 后添加新的数据结构
const orderTrendData = ref({
  today: 0,
  week: [0, 0, 0, 0, 0, 0, 0],
  month: new Array(30).fill(0)
})

// 系统动态数据
const systemActivities = ref([])

const theme = ref('light') // 可通过外部切换

// 定时轮询变量
let activitiesInterval = null

// 图表实例引用
const chartInstance = ref(null)

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    await Promise.all([
      fetchUsersCount(),
      fetchProductsCount(),
      fetchOrdersCount(),
      fetchDeliveriesCount()
    ]);
    ElMessage.success('仪表盘数据加载成功');
  } catch (error) {
    console.error('获取仪表盘数据失败:', error);
    ElMessage.error('获取仪表盘数据失败: ' + (error.message || '未知错误'));
  }
};

// 获取用户总数
const fetchUsersCount = async () => {
  try {
    const response = await request.get('/api/users/all/');
    
    if (response) {
      let userData = [];
      
      // 处理不同的响应数据结构
      if (Array.isArray(response)) {
        userData = response;
        stats.value.total_users = userData.length;
      } else if (response.results && Array.isArray(response.results)) {
        userData = response.results;
        stats.value.total_users = response.count || userData.length;
      } else if (response.items && Array.isArray(response.items)) {
        userData = response.items;
        stats.value.total_users = response.total || userData.length;
      }
      
      // 计算用户增长率（随机模拟）
      stats.value.user_growth = Math.floor(Math.random() * 10);
      
      console.log('用户总数:', stats.value.total_users);
    }
  } catch (error) {
    console.error('获取用户总数失败:', error);
    stats.value.total_users = 0;
  }
};

// 获取产品总数和低库存产品数
const fetchProductsCount = async () => {
  try {
    const response = await request.get('/api/products/');
    
    if (response) {
      let productsData = [];
      
      // 处理不同的响应数据结构
      if (Array.isArray(response)) {
        productsData = response;
        stats.value.total_products = productsData.length;
      } else if (response.results && Array.isArray(response.results)) {
        productsData = response.results;
        stats.value.total_products = response.count || productsData.length;
      } else if (response.items && Array.isArray(response.items)) {
        productsData = response.items;
        stats.value.total_products = response.total || productsData.length;
      }
      
      // 计算低库存产品数量
      stats.value.low_stock_products = productsData.filter(product => {
        const stock = product.stock_info && product.stock_info.length > 0 
          ? Number(product.stock_info[0].current_stock) || 0 
          : 0;
        const minStock = Number(product.min_stock || 10);
        return stock <= minStock && stock > 0;
      }).length;
      
      console.log('产品总数:', stats.value.total_products, '低库存产品数:', stats.value.low_stock_products);
    }
  } catch (error) {
    console.error('获取产品总数失败:', error);
    stats.value.total_products = 0;
    stats.value.low_stock_products = 0;
  }
};

// 获取订单总数和待处理订单数、趋势、分布
const fetchOrdersCount = async () => {
  try {
    const response = await request.get('/api/orders/', { params: { page_size: 1000 } });
    let ordersData = [];
    if (response.data && Array.isArray(response.data.items)) {
      ordersData = response.data.items;
      stats.value.total_orders = response.data.total || ordersData.length;
    } else if (Array.isArray(response.data)) {
      ordersData = response.data;
      stats.value.total_orders = ordersData.length;
    }
    stats.value.pending_orders = ordersData.filter(order => order.status === 'pending').length;
    
    // 订单分布
    const statusCounts = {};
    ordersData.forEach(order => {
      const status = order.status || 'unknown';
      statusCounts[status] = (statusCounts[status] || 0) + 1;
    });
    
    // 计算总数用于百分比
    const total = Object.values(statusCounts).reduce((sum, count) => sum + count, 0);
    
    stats.value.order_distribution = Object.entries(statusCounts).map(([status, count]) => ({
      status: getOrderStatusText(status),
      count,
      percentage: ((count / total) * 100).toFixed(1)
    }));
    
    // 订单趋势
    generateOrderTrendData(ordersData);
  } catch (error) {
    stats.value.total_orders = 0;
    stats.value.pending_orders = 0;
    stats.value.order_distribution = [];
    orderTrendData.value = { week: [0,0,0,0,0,0,0], month: new Array(30).fill(0) };
  }
}

// 获取配送任务总数和进行中数量
const fetchDeliveriesCount = async () => {
  try {
    const response = await request.get('/api/delivery-tasks/', { params: { page_size: 1000 } });
    let deliveries = [];
    if (response.data && Array.isArray(response.data.items)) {
      deliveries = response.data.items;
    } else if (Array.isArray(response.data)) {
      deliveries = response.data;
    }
    stats.value.total_deliveries = deliveries.length;
    stats.value.pending_deliveries = deliveries.filter(d => d.status === 'pending' || d.status === 'delivering').length;
  } catch (error) {
    stats.value.total_deliveries = 0;
    stats.value.pending_deliveries = 0;
  }
}

// 生成订单趋势数据
const generateOrderTrendData = (ordersData) => {
  // 初始化周和月的数据数组
  const weekData = new Array(7).fill(0);
  const monthData = new Array(30).fill(0);
  
  if (ordersData && ordersData.length > 0) {
    // 获取当前日期
    const now = new Date();
    const today = now.getDate();
    
    // 获取本周一的日期
    const monday = new Date(now);
    monday.setDate(now.getDate() - ((now.getDay() + 6) % 7));
    monday.setHours(0, 0, 0, 0);
    
    // 获取本月第一天的日期
    const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
    
    // 处理每个订单
    ordersData.forEach(order => {
      try {
        const orderDate = new Date(order.payment_time || order.created_at);
        
        // 更新周数据
        if (orderDate >= monday) {
          const dayOfWeek = (orderDate.getDay() + 6) % 7; // 转换为周一为0，周日为6
          weekData[dayOfWeek]++;
        }
        
        // 更新月数据
        if (orderDate >= firstDayOfMonth) {
          const dayOfMonth = orderDate.getDate() - 1; // 转换为0-based索引
          monthData[dayOfMonth]++;
        }
      } catch (e) {
        console.error('处理订单日期出错:', e);
      }
    });
  }
  
  // 更新图表数据
  orderTrendData.value = {
    week: weekData,
    month: monthData
  };
};

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消',
    delivering: '配送中',
    paid: '已支付'
  }
  return statusMap[status] || status
}


// 获取活动类型
const getActivityType = (type) => {
  const typeMap = {
    order: 'success',
    delivery: 'warning',
    product: 'info',
    user: 'primary',
    system: 'danger'
  }
  return typeMap[type] || 'info'
}

// 计算移动平均
const calculateMovingAverage = (data, window) => {
  const result = [];
  for (let i = 0; i < data.length; i++) {
    let sum = 0;
    let count = 0;
    for (let j = Math.max(0, i - window + 1); j <= i; j++) {
      if (data[j] > 0) {  // 只计入有效数据
        sum += data[j];
        count++;
      }
    }
    result.push(count > 0 ? sum / count : 0);
  }
  return result;
};

// 计算周期性指数
const calculateSeasonalIndex = (data, period) => {
  const seasonalIndices = new Array(period).fill(0);
  const counts = new Array(period).fill(0);
  
  // 计算每个周期位置的平均值
  for (let i = 0; i < data.length; i++) {
    if (data[i] > 0) {  // 只计入有效数据
      const idx = i % period;
      seasonalIndices[idx] += data[i];
      counts[idx]++;
    }
  }
  
  // 计算季节性指数
  const avgValue = data.reduce((sum, val) => sum + (val > 0 ? val : 0), 0) / 
                  data.filter(val => val > 0).length || 1;
  
  return seasonalIndices.map((sum, i) => {
    const avg = counts[i] > 0 ? sum / counts[i] : avgValue;
    return avg > 0 ? avg / avgValue : 1;
  });
};

// 计算订单趋势图表选项
const orderTrendOption = computed(() => {
  const data = userChartRange.value === 'week' ? orderTrendData.value.week : orderTrendData.value.month;
  const labels = userChartRange.value === 'week' 
    ? ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    : Array.from({length: 30}, (_, i) => `${i + 1}日`);
    
  const now = new Date();
  const currentIndex = userChartRange.value === 'week' 
    ? (now.getDay() + 6) % 7
    : now.getDate() - 1;
  
  const predictionData = [];
  const historyData = data.slice(0, currentIndex + 1);
  const validHistoryPoints = historyData.filter(v => v > 0);
  
  if (validHistoryPoints.length >= 3) {  // 需要更多历史数据来进行有效预测
    // 1. 计算移动平均
    const maWindow = userChartRange.value === 'week' ? 3 : 7;  // 周数据用3天，月数据用7天
    const movingAvg = calculateMovingAverage(historyData, maWindow);
    
    // 2. 计算周期性指数
    const period = userChartRange.value === 'week' ? 7 : Math.min(7, historyData.length);
    const seasonalIndices = calculateSeasonalIndex(historyData, period);
    
    // 3. 计算趋势
    const trendWindow = Math.min(5, historyData.length);  // 使用最近5个点计算趋势
    const recentData = movingAvg.slice(-trendWindow);
    let trend = 0;
    
    if (recentData.length >= 2) {
      // 计算最近数据的平均变化率
      for (let i = 1; i < recentData.length; i++) {
        if (recentData[i] > 0 && recentData[i-1] > 0) {
          trend += (recentData[i] - recentData[i-1]) / recentData[i-1];
        }
      }
      trend = trend / (recentData.length - 1);
      // 限制趋势的范围，避免过度预测
      trend = Math.max(-0.2, Math.min(0.2, trend));
    }
    
    // 4. 生成预测数据
    for (let i = 0; i < data.length; i++) {
      if (i <= currentIndex) {
        // 历史数据保持不变
        predictionData.push(data[i]);
      } else {
        // 预测未来数据
        const daysAhead = i - currentIndex;
        const seasonalIndex = seasonalIndices[i % period];
        const lastValue = predictionData[i-1] || movingAvg[movingAvg.length - 1] || 1;
        
        // 基础预测值 = 上一个值 * (1 + 趋势) * 季节性指数
        let baseValue = lastValue * (1 + trend) * seasonalIndex;
        
        // 添加受控的随机波动
        const volatility = Math.min(0.1, 0.02 * daysAhead);  // 波动随时间增加而增加，但有上限
        const randomFactor = 1 + (Math.random() * 2 - 1) * volatility;
        
        // 确保预测值在合理范围内
        baseValue = baseValue * randomFactor;
        baseValue = Math.max(lastValue * 0.7, Math.min(lastValue * 1.3, baseValue));  // 限制单日变化幅度
        
        predictionData.push(Math.round(baseValue));
      }
    }
  } else {
    // 历史数据不足时的简单预测
    const avgValue = validHistoryPoints.length > 0 
      ? validHistoryPoints.reduce((sum, val) => sum + val, 0) / validHistoryPoints.length 
      : 1;
    
    for (let i = 0; i < data.length; i++) {
      if (i <= currentIndex) {
        predictionData.push(data[i]);
      } else {
        const daysAhead = i - currentIndex;
        const volatility = Math.min(0.15, 0.03 * daysAhead);
        const randomFactor = 1 + (Math.random() * 2 - 1) * volatility;
        const baseValue = avgValue * randomFactor;
        predictionData.push(Math.round(baseValue));
      }
    }
  }

  return {
    title: {
      text: userChartRange.value === 'week' ? '本周订单趋势' : '本月订单趋势',
      left: 'center',
      top: 0,
      textStyle: {
        color: theme.value === 'dark' ? '#eee' : '#333',
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        const actualData = params[0]; // 实际数据
        const predictionData = params[1]; // 预测数据
        
        // 检测是否为今天之前的数据
        const index = actualData.dataIndex;
        const isHistory = index <= currentIndex;
        
        let tooltipText = actualData.axisValueLabel + '<br/>';
        tooltipText += actualData.marker + actualData.seriesName + ': ' + actualData.value + '<br/>';
        
        // 只有未来日期才显示"预测"标签
        if (isHistory) {
          tooltipText += predictionData.marker + predictionData.seriesName + ': ' + predictionData.value;
        } else {
          tooltipText += predictionData.marker + predictionData.seriesName + ' (预测): ' + predictionData.value;
        }
        
        return tooltipText;
      }
    },
    legend: {
      data: ['订单数量', '预测趋势'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: labels,
        axisLabel: {
          color: theme.value === 'dark' ? '#eee' : '#333'
        },
        axisPointer: {
          label: {
            formatter: function(params) {
              // 标记今天的位置
              return params.value + (params.dataIndex === currentIndex ? ' (今天)' : '');
            }
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '订单数量',
        axisLabel: {
          color: theme.value === 'dark' ? '#eee' : '#333',
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '订单数量',
        type: 'line',
        stack: '总量',
        smooth: true,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(83, 193, 87, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(83, 193, 87, 0.1)'
              }
            ]
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: data,
        itemStyle: {
          color: '#53c157'
        },
        lineStyle: {
          width: 2
        },
        symbol: 'circle',
        symbolSize: 8,
        markLine: {
          symbol: ['none', 'none'],
          label: {
            formatter: '今天',
            position: 'start'
          },
          lineStyle: {
            color: '#999',
            type: 'dashed'
          },
          data: [
            {
              xAxis: currentIndex
            }
          ]
        }
      },
      {
        name: '预测趋势',
        type: 'line',
        smooth: true,
        emphasis: {
          focus: 'series'
        },
        data: predictionData,
        itemStyle: {
          color: '#fdad58'
        },
        lineStyle: {
          width: 2,
          type: 'dashed'
        },
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  }
})

// 计算订单分布图表选项
const orderDistributionOption = computed(() => {
  const total = stats.value.order_distribution?.reduce((sum, item) => sum + item.count, 0) || 0;
  
  // 定义不同深浅的绿色
  const greenColors = [
    '#67C23A',  // 主题绿色
    '#85CE61',  // 浅绿色
    '#95D475',  // 更浅的绿色
    '#A5DA89',  // 最浅的绿色
    '#B5E09D',  // 极浅的绿色
    '#C5E6B1'   // 最浅的绿色
  ];
  
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#67C23A',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      }
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      textStyle: {
        color: '#333'
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {d}%',
          color: '#333'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
          }
        },
        data: stats.value.order_distribution?.map((item, index) => ({
          value: item.count,
          name: item.status,
          itemStyle: {
            color: greenColors[index % greenColors.length]
          }
        })) || []
      }
    ]
  }
})

// 处理图表大小变化
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize();
  }
}

// 监听窗口大小变化
onMounted(() => {
  fetchDashboardData()
  fetchSystemActivities()
  // 每10秒刷新一次系统动态
  activitiesInterval = setInterval(fetchSystemActivities, 10000)
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  if (activitiesInterval) {
    clearInterval(activitiesInterval)
    activitiesInterval = null
  }
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})

// 监听图表范围变化
watch(userChartRange, () => {
  // 更新图表数据
  if (chartInstance.value) {
    chartInstance.value.setOption(orderTrendOption.value)
  }
})

// 监听订单趋势数据变化
watch(orderTrendData, () => {
  // 更新图表数据
  if (chartInstance.value) {
    chartInstance.value.setOption(orderTrendOption.value)
  }
}, { deep: true })

// 获取系统动态（订单+配送任务+配送状态）
const fetchSystemActivities = async () => {
  try {
    // 1. 获取订单
    const ordersRes = await request.get('/api/orders/', { params: { page_size: 1000 } })
    let orders = []
    if (ordersRes.data && Array.isArray(ordersRes.data.items)) {
      orders = ordersRes.data.items
    } else if (Array.isArray(ordersRes.data)) {
      orders = ordersRes.data
    }
    // 2. 获取配送任务
    const tasksRes = await request.get('/api/delivery-tasks/', { params: { page_size: 1000 } })
    let tasks = []
    if (tasksRes.data && Array.isArray(tasksRes.data.items)) {
      tasks = tasksRes.data.items
    } else if (Array.isArray(tasksRes.data)) {
      tasks = tasksRes.data
    }
    // 3. 获取配送状态记录
    const statusRes = await request.get('/api/delivery-status-records/', { params: { page_size: 1000 } })
    let statusRecords = []
    if (statusRes.data && Array.isArray(statusRes.data.items)) {
      statusRecords = statusRes.data.items
    } else if (Array.isArray(statusRes.data)) {
      statusRecords = statusRes.data
    }
    // 4. 组装系统动态
    const activities = []
    // 🛒 客户下单
    orders.forEach(order => {
      if (order.payment_time) {
        activities.push({
          type: 'order',
          icon: 'ShoppingCart',
          color: 'primary',
          time: order.payment_time,
          content: `🛒 客户 ${order.customer_name || ''} 下单，订单号：${order.order_number}`
        })
      }
    })
    // 👨‍🍳 订单分配
    tasks.forEach(task => {
      if (task.status === 'assigned' && task.deliveryman_name) {
        activities.push({
          type: 'assign',
          icon: 'User',
          color: 'info',
          time: task.updated_at,
          content: `👨‍🍳 订单分配给 ${task.deliveryman_name}，订单号：${task.order_number}`
        })
      }
    })
    // 🚚 配送状态（包括已配送）
    statusRecords.forEach(record => {
      if ([
        'delivering',
        'assigned',
        'delivered', // 新增已配送
      ].includes(record.status)) {
        activities.push({
          type: 'delivery',
          icon: 'Van',
          color: record.status === 'delivered' ? 'primary' : 'success',
          time: record.created_at,
          content: `🚚 配送状态：${getStatusText(record.status)}，订单号：${record.delivery_task?.order_number || ''}`
        })
      }
    })
    // ✅ 订单完成
    orders.forEach(order => {
      if (order.status === 'completed') {
        activities.push({
          type: 'completed',
          icon: 'Check',
          color: 'success',
          time: order.updated_at,
          content: `✅ 订单完成，订单号：${order.order_number}`
        })
      }
    })
    // ⚠️ 异常事件
    orders.forEach(order => {
      if (['cancelled', 'returned', 'exception'].includes(order.status)) {
        activities.push({
          type: 'exception',
          icon: 'Warning',
          color: 'danger',
          time: order.updated_at,
          content: `⚠️ 订单${getStatusText(order.status)}，订单号：${order.order_number}`
        })
      }
    })
    // 按时间倒序
    activities.sort((a, b) => new Date(b.time) - new Date(a.time))
    systemActivities.value = activities
  } catch (error) {
    systemActivities.value = []
  }
}

// 优化 getStatusText 方法，支持更多状态
const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    assigned: '已分配',
    delivering: '配送中',
    delivered: '已配送',
    completed: '已完成',
    cancelled: '已取消',
    returned: '已退货',
    paid: '已付款',
    shipped: '已发货',
    processing: '处理中',
    exception: '异常',
    unknown: '未知'
  }
  return statusMap[status] || status
}
</script>

<style scoped>
.admin-dashboard {
  padding: 24px;
}
.dashboard-stats {
  margin-top: 24px;
}
.dashboard-stats .el-card {
  height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.dashboard-charts {
  margin-top: 24px;
}
.stat-title {
  font-size: 16px;
  color: #888;
}
.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-top: 8px;
}
.stat-trend {
  margin-top: 8px;
  font-size: 14px;
  color: #909399;
}
.stat-trend .up {
  color: #67C23A;
}
.stat-trend .down {
  color: #F56C6C;
}
.chart-card {
  margin-bottom: 20px;
}
.chart {
  height: 300px;
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.timeline-card {
  margin-top: 20px;
}
/* 新增：系统动态滚动区域样式 */
.timeline-scroll-card {
  height: 340px;
  display: flex;
  flex-direction: column;
}
.timeline-scroll-content {
  flex: 1;
  overflow-y: auto;
  max-height: 260px;
  padding-right: 8px;
}
.activity-cards {
  display: flex;
  flex-direction: column;
  gap: 14px;
}
.activity-card {
  display: flex;
  align-items: center;
  background: #e8f8ee;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 16px 18px;
  transition: box-shadow 0.18s cubic-bezier(.4,1.3,.6,1);
  cursor: pointer;
}
.activity-card:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.10);
}
.activity-icon {
  margin-right: 18px;
  font-size: 22px;
  color: #67c23a;
  flex-shrink: 0;
}
.activity-content {
  flex: 1;
  font-size: 15px;
  color: #222;
  margin-left: 8px;
}
.activity-time {
  color: #999;
  font-size: 13px;
  margin-left: 18px;
  flex-shrink: 0;
}
</style> 